/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.eng.scc.core.view;

import com.eng.scc.core.data.Company;
import com.eng.scc.core.data.Device;
import com.eng.scc.core.data.Vehicle;
import com.eng.scc.core.db.manager.service.FuelControllerManagerService;
import com.eng.scc.core.details.CompanyDetails;
import com.eng.scc.core.details.VehicleDetails;
import com.eng.scc.core.editors.VehicleEditor;
import com.eng.scc.core.panes.DeviceDataPane;
import com.eng.scc.core.parts.AbstractApplicationAction;
import com.eng.scc.core.parts.ActionCategory;
import com.eng.scc.core.parts.SummaryPane;
import com.eng.scc.core.parts.VehiclesTree;
import com.eng.scc.core.util.HTMLFactory;
import com.eng.scc.core.util.ImageFinder;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

/**
 *
 * @author Rafael
 */
public class VehicleApplicationView extends ApplicationView
{

    public VehicleApplicationView()
    {
        initComponets();
    }

    @Override
    public void refreshContent()
    {
        try
        {
            vehiclesTree.buildTree();
        }
        
        catch ( Exception e )
        {
            ApplicationContext.getInstance().saveLog( e );
        }
    }
    
    private void find()
    {
//        try
//        {
//            if ( ! tfSearch.getText().isEmpty() )
//            {
//                clientsTable.setClients( DatabaseManagerService.getInstance().findByName( tfSearch.getText() ) );
//            }
//            
//            else
//            {
//                refreshContent();
//            }
//        }
//        catch ( Exception e )
//        {
//            ApplicationContext.getInstance().saveLog( e );
//        }
    }
    
    private void updateItemSelected()
    {
        try
        {
            panels.removeAll();
            panels.addTab( "Resumo", summaryPane );
            
            Object o = getSelectedObject();

            if ( o instanceof Company )
            {
                summaryPane.setContent( CompanyDetails.getDetails( ( Company ) o ) );
            }
            else if ( o instanceof Vehicle )
            {
                summaryPane.setContent( VehicleDetails.getDetails( ( Vehicle ) o ) );
                panels.addTab( "Leituras", paneDevice );
            }
            else
            {
                summaryPane.setContent( HTMLFactory.Body.EMPTY );
            }
        }
        
        catch ( Exception e )
        {
            ApplicationContext.getInstance().saveLog( e );
        }
    }
    
    private void initComponets()
    {
       setLayout( new GridBagLayout() );
       
       btSearch.setIcon( ImageFinder.getImageIcon( "bt_search.png") );
       
       btSearch.addActionListener( new ActionListener() 
       {
            @Override
            public void actionPerformed( ActionEvent e )
            {
                find();
            }
        });
       
       tfSearch.addActionListener( new ActionListener() 
       {
            @Override
            public void actionPerformed( ActionEvent e )
            {
                find();
            }
        });

       vehiclesTree.addTreeSelectionListener( new TreeSelectionListener()
        {
            @Override
            public void valueChanged( TreeSelectionEvent e )
            {
                updateItemSelected();
            }
        } );
        
       
       vehiclesTree.addMouseListener( new MouseAdapter()
       {
           @Override
           public void mouseClicked( MouseEvent e )
           {
               if ( e.getClickCount() >= 2 && getSelectedObject() instanceof Vehicle)
               {
                   edit();
               }
           }
        });
       
        add( lbSearch, 
                new GridBagConstraints( 1, 0, 1, 1, 0.0, 0.0,
                                        GridBagConstraints.WEST, 
                                        GridBagConstraints.NONE, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        add( tfSearch, 
                new GridBagConstraints( 2, 0, 1, 1, 1.0, 0.0,
                                        GridBagConstraints.WEST,  
                                        GridBagConstraints.HORIZONTAL, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        add( btSearch, 
                new GridBagConstraints( 3, 0, 1, 1, 0.0, 0.0, 
                                        GridBagConstraints.WEST, 
                                        GridBagConstraints.NONE, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        
        paneScroll.setViewportView( vehiclesTree );
        splitPane.setLeftComponent( paneScroll );
        splitPane.setDividerLocation( 0.2 );
        splitPane.setRightComponent( panels );
        
        add( splitPane, 
                new GridBagConstraints( 1, 1, 3, 1, 1.0, 1.0, 
                                        GridBagConstraints.NORTH, 
                                        GridBagConstraints.BOTH, 
                                        new Insets( 5, 5, 5, 5 ), 0, 0 ) );
        
        panels.addChangeListener( new ChangeListener()
        {
           @Override
           public void stateChanged( ChangeEvent e )
           {
               if ( panels.getSelectedIndex() == 1 )
               {
                   try
                   {
                        Vehicle v = (Vehicle) getSelectedObject();

                        Device d = FuelControllerManagerService.getInstance().getDevice( v.getId() );

                        if ( d != null )
                        {
                            paneDevice.setDeviceID( d.getId() );
                        }
                   }
                   
                   catch ( Exception s )
                   {
                       s.printStackTrace();
                   }
               }
           }
       });
    }
    
    public void add()
    {
        try
        {
            Vehicle vehicle = new Vehicle();
            
            if ( VehicleEditor.edit( this, vehicle ) )
            {
                FuelControllerManagerService.getInstance().addVehicle( vehicle );                           
                
                refreshContent();
            }
        }
        
        catch ( Exception e )
        {
            ApplicationContext.getInstance().saveLog( e );
        }
    }
    
    public void delete()
    {
        if ( getSelectedObject() != null && getSelectedObject() instanceof Vehicle )
        {
            try
            {
                if ( JOptionPane.showConfirmDialog( this, "Deseja Excluir o veículo selecionado?" ) == JOptionPane.YES_OPTION )
                {
                    FuelControllerManagerService.getInstance().deleteVehicle( (Vehicle)getSelectedObject() );

                    refreshContent();
                }
            }
            
            catch ( Exception e )
            {
                ApplicationContext.getInstance().saveLog( e );
            }
        }
        
        else
        {
            JOptionPane.showMessageDialog( this, "Selecione um Veículo na tabela!" );
        }
    }    
    
    private Object getSelectedObject()
    {
        if ( vehiclesTree.getSelectionPath() != null )
        {
//            if ( ((DefaultMutableTreeNode) driversTree.getSelectionPath().getLastPathComponent() ).getUserObject() instanceof Driver )
            {
                return ((DefaultMutableTreeNode) vehiclesTree.getSelectionPath().getLastPathComponent() ).getUserObject();
            }
        }
        
        return null;
    }
    
    public void edit()
    {
        try
        {
            if ( getSelectedObject() != null )
            {
                Vehicle v = (Vehicle) getSelectedObject();
                
                if ( VehicleEditor.edit( this, v ) )
                {
                    FuelControllerManagerService.getInstance().updateVehicle( v );
                    
                    refreshContent();
                }
            }

//            else
//            {
//                JOptionPane.showMessageDialog( this, "Selecione um Veículo na tabela!" );
//            }
        }
        
        catch ( Exception e )
        {
            ApplicationContext.getInstance().saveLog( e );
        }
    }

    @Override
    public List<ActionCategory> getViewActions()
    {
        List<ActionCategory> categorys = new ArrayList<ActionCategory>();
        categorys.add( new ActionCategory( "Veículos", new AbstractApplicationAction[]
        {
            btAdd,
            btEdit,
            btDelete,
            btPrint
        }) );
        return categorys;
    }
    
    protected AbstractApplicationAction btPrint = new AbstractApplicationAction( "Imprimir", "tb_print.png" )
    {
        @Override
        public void actionPerformed( ActionEvent e )
        {
//            Database.runReport( "full_client_report.jasper" );
        }
    };
    
    private VehiclesTree vehiclesTree = new VehiclesTree();
    private JScrollPane paneScroll = new JScrollPane();
    private JSplitPane splitPane = new JSplitPane();
    private SummaryPane summaryPane = new SummaryPane();
    private JLabel lbSearch = new JLabel( "Buscar:" );
    private JTextField tfSearch = new JTextField();
    private DeviceDataPane paneDevice = new DeviceDataPane();
    private JTabbedPane panels = new JTabbedPane();
    
    private JButton btSearch = new JButton();
}
